<?php

namespace app\admin\controller\user;

use app\common\controller\Backend;
use app\common\library\Auth;
use app\common\library\Token;
use fast\Random;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Hook;
use function EasyWeChat\Kernel\Support\get_server_ip;

/**
 * 会员管理
 *
 * @icon fa fa-user
 */
class User extends Backend
{
    //Token默认有效时长
    protected $keeptime   = 2592000;

    protected $relationSearch = true;
    protected $searchFields   = 'id,username,nickname';

    /**
     * @var \app\admin\model\User
     */
    protected $model = null;
    /**
     * @var string
     */
    private $_token;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\User;
        $this->view->assign("positionList", $this->model->getPositionList());
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->with('group')
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $k => $v) {
                $v->avatar = $v->avatar ? cdnurl($v->avatar, true) : letter_avatar($v->nickname);
                $v->hidden(['password', 'salt']);
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = input();
        $params = $params['row'];
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name     = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }

            $params['createtime'] = time();
            $params['jointime']   = time();
            $params['joinip']     = get_server_ip();
            $params['loginip']    = get_server_ip();
            if (empty($params['password'])) $params['password'] = '123456';
            $issetMobile = $this->model->where('mobile', $params['mobile'])->find();
            if ($issetMobile) $this->error('相同手机号已存在');
            $issetCompere = $this->model->where(['position' => 2, 'username' => $params['username']])->find();
            if ($issetCompere) $this->error('主持人身份下,相同用户名已存在');
            $result = $this->model->allowField(true)->create($params);
            $number = numberEncode($result->id);
            $this->_token = Random::uuid();
            Token::set($this->_token, $result->id, $this->keeptime);
            $this->model->where('id',$result->id)->update(['number'=>$number,'token'=>$this->_token,'status'=>'normal']);
            //注册成功的事件
            $this->_user = \app\common\model\User::get($result->id);
            Hook::listen("user_login_successed", $this->_user);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        if ($this->request->isPost()) {
            $this->token();
        }
        $row                 = $this->model->get($ids);
        $this->modelValidate = false;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $this->view->assign('groupList', build_select('row[group_id]', \app\admin\model\UserGroup::column('id,name'), $row['group_id'], ['class' => 'form-control selectpicker']));
        return parent::edit($ids);
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids                 = $ids ? $ids : $this->request->post("ids");
        $row                 = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        Auth::instance()->delete($row['id']);
        $this->success();
    }

    /**
     * 主持人
     */
    public function compere()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
//            if ($this->request->request('keyField')) {
//                return $this->selectpage();
//            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $otherWhere['position'] = 2;
            $arr                    = input();
            if (isset($arr['keyValue']) && !empty($arr['keyValue'])) $otherWhere['id'] = $arr['keyValue'];
            $list = $this->model
                ->where($where)
                ->where($otherWhere)
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $k => $v) {
                $v->avatar = $v->avatar ? cdnurl($v->avatar, true) : letter_avatar($v->nickname);
                $v->hidden(['password', 'salt']);
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }
}
